import json
import re

from django.contrib.auth import logout
from django.http import JsonResponse
from django.views import View

from areas.models import Area
from django.core.cache import cache
import logging
logger = logging.getLogger('django')
from users.models import Address, User


class AreasProvince(View):

    def get(self,request):

        province_list = cache.get("province_list")

        if not province_list:

            try:
                province_list_data = Area.objects.filter(parent__isnull=True)

                province_list =[]

                for province_data in province_list_data:
                    province_list.append({'id':province_data.id,
                                 'name':province_data.name})

            except Exception as e:

                return JsonResponse({'code':400,
                                     'ermsg':'访问数据库失败'})

            cache.set('province_list',province_list,3600)

        return JsonResponse({"code":0,
                             'errmsg':'ok',
                             'province_list':province_list})



class SubAreasView(View):


    def get(self, request, pk):

        sub_data = cache.get('sub_area_'+pk)

        if not sub_data:

            try:
                 # 1.查询市或区数据
                sub_model_list = Area.objects.filter(parent=pk)
                 #  查询省份数据
                parent_model = Area.objects.get(id=pk)

                # 2.整理市或区数据
                sub_list = []
                for sub_model in sub_model_list:
                    sub_list.append({'id': sub_model.id,
                                     'name': sub_model.name})

                sub_data = {
                    'id': parent_model.id,  # pk
                    'name': parent_model.name,
                    'subs': sub_list
                }

                cache.set('sub_data', sub_data, 3600)

            except Exception as e:
                return JsonResponse({'code': 400,
                                     'errmsg': '城市或区县数据错误'})

        # 3.响应市或区数据 ok: 0
        return JsonResponse({'code': 0,
                                  'errmsg': 'OK',
                                  'sub_data': sub_data})


class CreateAddressView(View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""

        # 获取地址个数:
        try:
           count = Address.objects.filter(user=request.user,
                                       is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                      'errmsg': '获取地址数据出错'})
        # 判断是否超过地址上限：最多20个
        if count >= 20:
            return JsonResponse({'code': 400,
                                      'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                      'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address':address_dict})

class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                  # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({'code':0,
                                  'errmsg':'ok',
                                  'addresses':address_dict_list,
                                  'default_address_id':default_id})

class UpdateDeleteAddress(View):
    def put(self,request,address_id):

        dict = json.loads(request.body.decode())

        receiver = dict.get('receiver')
        province_id = dict.get('province_id')
        city_id = dict.get('city_id')
        district_id = dict.get('district_id')
        place= dict.get('place')
        mobile = dict.get('mobile')
        tel = dict.get('tel')
        email = dict.get('email')

        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少必传的参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        try:

            address = Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email)
        except Exception as e:

            return JsonResponse({'code':400,
                                 'errmsg':'更新数据库失败'})
        address = Address.objects.get(id=address_id)

        address_dict = {
            'id':address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'address':address_dict})

    def delete(self,request,address_id):

        try:

            address = Address.objects.get(id=address_id)

            address.is_deleted = True
            address.save()

        except Exception as e:

            return JsonResponse({'code':400,
                                 'errmsg':'删除数据失败'})

        return JsonResponse({'code':0,
                             'errmsg':'ok'})

class DefaultAddress(View):
    def put(self,request,address_id):

        try:

            address = Address.objects.get(id=address_id)

            request.user.default_address = address
            request.user.save()

        except Exception as e:

            return JsonResponse({'code':400,
                                  'errmsg':'设置默认地址失败'})
        return JsonResponse({'code':0,
                             'errmsg':'ok'})

class ChangeAddressTitle(View):
    def put(self,request,address_id):

        dict = json.loads(request.body.decode())

        title = dict.get('title')

        try:

            address = Address.objects.get(id=address_id)

            address.title = title
            address.save()

        except Exception as e:

            return JsonResponse({'code':400,
                                  'errmsg':'修改地址失败'})

        return JsonResponse({'code':0,
                             'errmsg':'ok'})

class ChangePassword(View):

    def put(self,request):

        dict = json.loads(request.body.decode())

        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        if not all([old_password,new_password,new_password2]):

            return JsonResponse({'code':400,
                                 'errmsg':'缺少必传的参数'})

        res = request.user.check_password(old_password)

        if res is None:

            return JsonResponse({'code':400,
                                 'errmsg':'验证旧密码失败'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一致'})
        try:

           request.user.set_password(new_password2)
           request.user.save()

        except Exception as e:

            return JsonResponse({'code': 400,
                                 'errmsg': '修改密码失败'})

        logout(request)


        response =  JsonResponse({'code':0,
                             'errmsg':'ok'})

        response.delete_cookie('username')

        return response





